package cn.ydt.ydt.resource.controller;

import cn.ydt.ydt.common.resful.JsonResult;
import cn.ydt.ydt.common.resful.StatusCode;
import cn.ydt.ydt.resource.utils.RenameUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;

@Api(tags = "文件上传模块")
@Slf4j
@RestController
@RequestMapping("/upload")
public class FileUploadController {

    @Value("${SavePath.uploadPath}")
    private String uploadPath;   //图标图片存储路径
    @Value("${SavePath.getPath}")
    private String getPath;   //图标映射路径

    /**
     * 文件上传
     * @param file 图片资源
     * @return 图映射的虚拟访问路径
     */

    @ApiOperation("单张图片上传接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file",value = "上传文件",required = true,dataType = "MultipartFile")
    })
    @PostMapping("/file")
    public JsonResult profilePhotoUpload( MultipartFile file){
            //获取文件名
            String fileName = file.getOriginalFilename();
            //更新文件名，防止文件名重复
            String newFileName = RenameUtils.generateFileName(fileName);
            try {
                //transferTo方法用于将图片保存到文件夹里
                file.transferTo(new File(uploadPath+newFileName));
                String url = getPath+newFileName;
                return JsonResult.ok(url,"文件上传成功！");
            } catch (Exception e) {
                e.printStackTrace();
                return JsonResult.failed(StatusCode.FAIL_FILEUPLOAD,"文件上传失败");
            }
    }

}
